﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace GPMS.Web.Controllers
{
    using GPMS.Model;
    using GPMS.Web.Controllers.Filters;
    /// <summary>
    /// 控制器基类
    /// </summary>
    [AuthorizationFilter]
    public class BaseController : Controller
    {
        public ExtendedGPMSDb gpmsDb = new ExtendedGPMSDb();

        public ActionResult Success(string msg)
        {
            ViewData["msg"] = string.IsNullOrEmpty(msg) ? "操作成功" : msg;
            return PartialView("Success");
        }

        public ActionResult JsonError(string msg)
        {
            var json = new Dictionary<string, object> { 
                { "error", true }, 
                { "msg",string.IsNullOrEmpty(msg)?"发生错误啦!":msg } 
            };
            return Json(json, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Confirm(string msg)
        {
            ViewData["msg"] = string.IsNullOrEmpty(msg) ? "确定执行此操作吗？" : msg;
            return PartialView("Confirm");
        }

        public ActionResult Error(string msg)
        {
            ViewData["msg"] = string.IsNullOrEmpty(msg) ? "发生错误啦！！" : msg;
            return PartialView("Error");
        }

        [NonAction]
        public static string GetError(ModelStateDictionary modelState)
        {
            var errorMsg = modelState.Keys.Select(key => modelState[key].Errors.FirstOrDefault()).
                Where(error => error != null).Aggregate("", (current, error) => current += (error.ErrorMessage + "\r\n"));
            return errorMsg;
        }
    }
}
